package 回溯;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tmh
 * @date 2024/9/12 17:37
 * @description
 */
public class T22括号生成 {
    List<String> result = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        valid(0, 0, n, "");
        return result;
    }

    public void valid(int left, int right, int n, String s) {
        //如果左括号的个数=右括号的个数，那么就说明这个括号有效
        if (left == n && right == n) {
            result.add(s);
        }
        //先添加左括号
        if (left < n) {
            valid(left + 1, right, n, s + "(");
        }
        //在添加右括号
        if (right < left) {
            valid(left, right + 1, n, s + ")");
        }
    }
}
